package com.chzc.fm.duotin.ui.home;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chzc.fm.duotin.R;
import com.chzc.fm.duotin.adapter.viewpager.HomeMyPagerAdapter;
import com.chzc.fm.duotin.bean.home.PlayListBean;
import com.chzc.fm.duotin.event.PlayListEvent;
import com.chzc.fm.duotin.ui.home.utils.FragmentPlayList;
import com.chzc.fm.duotin.ui.home.utils.HomeUtils;
import com.chzc.fm.duotin.utils.DuotinTask;
import com.chzc.fm.duotin.utils.FastBlur;
import com.chzc.fm.duotin.utils.FileUtils;
import com.chzc.fm.duotin.utils.HttpUtil;
import com.chzc.fm.duotin.utils.Unicode2CN;
import com.lzy.widget.PullZoomView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class PullListViewActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private ViewPager viewPager;
  // LayoutInflater inflater;
    private ImageView ivBackground;
    private TextView tvBtnAllPlayList,tvBtnDownLoad;
    private ImageView ivDot1,ivDot2;
    //存储小圆点
    private List<ImageView> mIvDotList=new ArrayList<>();
    //标题栏
    private TextView tvTitle;
    private ImageView ivBack;
    //升序与排序
    private ImageView ivSort;
    //全部节目的数据
    private List<PlayListBean.ContentListBean.DataListBean> dataList;

    //判断是升序还是降序
    boolean isAes = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pull_listview);

        initView();
        initEvent();

        Intent intent = getIntent();
        String needAddId = intent.getStringExtra("urlID");
        //获取数据
        HomeUtils.getDownLoadList(new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {
                //将GBK格式转换为unicode
                String orignData = Unicode2CN.unicode2GBK(object.toString());
                try {
                    JSONObject root = new JSONObject(orignData);
                    String message = root.getString("error_msg");
                    if ("SUCCESS".equals(message)) {
                        final JSONObject data = root.getJSONObject("data");
                        //获取到整个的json格式数据
                        final PlayListBean playList = PlayListBean.objectFromData(data.toString());
                        //设置背景图片
                        String imgBurl = playList.getAlbum().getImage_url();
                        setBackgroundPicture(imgBurl);
                        //设置内容
                        final HomeMyPagerAdapter vpAdapter = new HomeMyPagerAdapter(PullListViewActivity.this,playList);
                        viewPager.setAdapter(vpAdapter);

                        //设置播放页面的数据
                        dataList = playList.getContent_list().getData_list();
                        tvBtnAllPlayList.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tvBtnAllPlayList.setSelected(true);
                                tvBtnDownLoad.setSelected(false);
                                Toast.makeText(PullListViewActivity.this, "点击了那个", Toast.LENGTH_SHORT).show();
                                FragmentManager manager = getSupportFragmentManager();
                                FragmentTransaction transaction = manager.beginTransaction();
                                transaction.replace(R.id.fragment_container,new FragmentPlayList(dataList)).commit();
                            }
                        });

                        //标题栏文字
                        tvTitle.setText(playList.getAlbum().getTitle());


                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void error(String msg) {

            }
        },needAddId);
        boolean isZoomEnable = intent.getBooleanExtra("isZoomEnable", true);
        PullZoomView pzv = (PullZoomView) findViewById(R.id.pzv);
        pzv.setIsParallax(false);
        pzv.setIsZoomEnable(isZoomEnable);
        pzv.setSensitive(1.5f);
        pzv.setZoomTime(500);
        pzv.setOnScrollListener(new PullZoomView.OnScrollListener() {
            @Override
            public void onScroll(int l, int t, int oldl, int oldt) {
                System.out.println("onScroll   t:" + t + "  oldt:" + oldt);
            }

            @Override
            public void onHeaderScroll(int currentY, int maxY) {
                System.out.println("onHeaderScroll   currentY:" + currentY + "  maxY:" + maxY);
            }

            @Override
            public void onContentScroll(int l, int t, int oldl, int oldt) {
                System.out.println("onContentScroll   t:" + t + "  oldt:" + oldt);
            }
        });
    }

    private void setBackgroundPicture(final String imgBurl) {

        new DuotinTask(new DuotinTask.IRequest() {
            @Override
            public Object doRequest() {

               File file = HttpUtil.download(imgBurl, FileUtils.DIR_IMAGE,FileUtils.getFileNameByHashCode(imgBurl),null);

                return file;
            }
        }, new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {
                //设置模糊背景图片
                File file  = (File) object;
                Bitmap background = BitmapFactory.decodeFile(file.getAbsolutePath());
                FastBlur.blur(PullListViewActivity.this,background,ivBackground);
            }

            @Override
            public void error(String msg) {

            }
        }).execute();

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(this, "点击了" + position, Toast.LENGTH_SHORT).show();
    }

    private void initView(){

        //设置内容的viewPager
        //设置头部的布局
        viewPager = (ViewPager) findViewById(R.id.vpTop);
        //绑定背景
        ivBackground = (ImageView) findViewById(R.id.ivBackground);
        //滚动小圆点
        ivDot1 = (ImageView) findViewById(R.id.iv_dot1);
        ivDot2 = (ImageView) findViewById(R.id.iv_dot2);
        mIvDotList.add(ivDot1);
        mIvDotList.add(ivDot2);
        //标题栏
        tvTitle = (TextView) findViewById(R.id.tv_title);
        ivBack = (ImageView) findViewById(R.id.iv_back);


        //设置总播放页数
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fragment_container,new FragmentPlayListCount()).commit();
        //播放列表界面的listview
       /* final ListView playlist = (ListView) findViewById(R.id.list_playlist);
        playlist.setEmptyView(findViewById(R.id.defaults_show_list));*/

        //点击事件的textView

        tvBtnAllPlayList = (TextView) findViewById(R.id.tv_alllist);
        tvBtnDownLoad = (TextView) findViewById(R.id.tv_downLoade);
        //排序
        ivSort = (ImageView) findViewById(R.id.iv_sort);
    }

    private void initEvent(){
        //设置按钮点击事件
        tvBtnDownLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvBtnDownLoad.setSelected(true);
                tvBtnAllPlayList.setSelected(false);
                FragmentManager manager = getSupportFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.fragment_container,new FragmentPlayListCount()).commit();
            }
        });
        //设置viewPager
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                //设置滑动监听

                for (int i = 0; i < mIvDotList.size(); i++) {
                    if (position==i){
                        mIvDotList.get(i).setImageDrawable(getResources().getDrawable(R.drawable.ic_album_dot_selected));
                    }else{
                        mIvDotList.get(i).setImageDrawable(getResources().getDrawable(R.drawable.ic_album_dot_unselected));
                    }

                }


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //回退事件
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ivSort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isAes){

                    Comparator<PlayListBean.ContentListBean.DataListBean> ascComparator = new PlayListCompartor();
                    //排序后的集合
                    //利用Collections类静态工具方法对集合dataList进行排序
                    //降序
                    Comparator<PlayListBean.ContentListBean.DataListBean>desComparator =Collections.reverseOrder(ascComparator);
                    Collections.sort(dataList,desComparator);
                    //在这里post通知fragment数据已经改变
                    EventBus.getDefault().post(new PlayListEvent());
                    isAes = false;

                }else {

                    Comparator<PlayListBean.ContentListBean.DataListBean> ascComparator = new PlayListCompartor();
                    //排序后的集合
                    //利用Collections类静态工具方法对集合dataList进行排序
                    //升序
                    Collections.sort(dataList,ascComparator);
                    isAes = true;
                }



                //在这里post通知fragment数据已经改变
                EventBus.getDefault().post(new PlayListEvent());
            }
        });

    }


    //这里是按降序排列
    public class PlayListCompartor implements Comparator<PlayListBean.ContentListBean.DataListBean>{

        @Override
        public int compare(PlayListBean.ContentListBean.DataListBean lhs, PlayListBean.ContentListBean.DataListBean rhs) {
            return lhs.getPlay_num()-rhs.getPlay_num();
        }
    }


    private void initData(){

       // tvTitle.setText();

    }



    }


